package com.game.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

import com.game.config.Config;
import com.game.layer.BasicLayer;

/**
 * 图片处理类*/
public class ImageTool {
	public static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
	public static HashMap<String, SoftReference<Bitmap[]>> imageArrayCache = new HashMap<String, SoftReference<Bitmap[]>>();
	//用于解密图片
	public static final int pre_length=3;
	public static final int beh_length=3;
	//用于获取asserts图片
	public static AssetManager assetManager;
	public static Resources res;
	//静态实例,单例
	public static ImageTool instance;
	
	public static Paint paint;
	
	//图片缩放矩阵,处理不同大小版本的图片
	public static Matrix imageScaleMx = null;
	//缩放矩阵,用于自适应屏幕绘制图片
	public static Matrix scaleMX;
	
	public static ImageTool newInstance(Resources res){
		ImageTool.assetManager=res.getAssets();
		ImageTool.res=res;
		ImageTool.instance=new ImageTool();
		paint=Tools.createNewPaint();
		/*设置缩放矩阵*/
		resetScaleMX();
		//初始化缩放矩阵
//		imageScaleMx = new Matrix();
//		imageScaleMx.postScale(2.5f, 2.5f);
		return instance;
	}
	
	public static AssetManager getAssetManager(){
		return assetManager;
	}
	
	
	/**
	 * 获取图片缓存库
	 * @return
	 */
	public static String getImageCondition(){
		int total =0;
		int exist =0;
		for(String key : imageCache.keySet()){
			total++;
			if(imageCache.get(key)!=null){
				exist++;
			}
		}
		return "图片 全部:"+total+"个,存在:"+exist+"个";
	}
	
	public static void resetScaleMX(){
		/*如果需要缩放*/
		if(PhoneInfo.scale){
			/*非全屏,则实例化scaleMX*/
			if(!Config.FULL_SCREEN){
				setScaleMX();
			}
			/*全屏*/
			else{
				setScaleMXFullScreen();
			}
		}
		
	}
	
	/**
	 * 实例化scaleMX,不会走样的拉伸*/
	public static void setScaleMX(){
		scaleMX=new Matrix();
		float scale=(PhoneInfo.scaleX-PhoneInfo.scaleY)>0?PhoneInfo.scaleY:PhoneInfo.scaleX;
		scaleMX.postScale(scale,scale);
		PhoneInfo.resetScreen();
	}
	
	/**
	 * 实例化scaleMX,会走样的拉伸*/
	public static void setScaleMXFullScreen(){
		scaleMX=new Matrix();
		scaleMX.postScale(PhoneInfo.scaleX,PhoneInfo.scaleY);
		PhoneInfo.resetScreen();
	}
	
	/**
	 * 移除scaleMX,原图大小显示*/
	public static void removeScaleMX(){
		scaleMX=null;
	}
	
	/**获取drawable中的图片**/
	public static Bitmap getBitMap(int id){
		return BitmapFactory.decodeResource(res, id);
	}
	
	/**获取drawable中的图片**/
	public static Bitmap getBitMapRaw(int id){
		try{
			InputStream is=res.openRawResource(id);
			Bitmap bmp= BitmapFactory.decodeStream(is);
			is.close();
			return bmp;
		}catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**获取asset中的图片,强制缩放
	 * @param fileName 文件名
	 * **/
	public static Bitmap getBitMapForceScale(String fileName){
		return getBitMapForceScale(fileName,scaleMX);
	}
	
	/**获取asset中的图片,自带缩放
	 * @param fileName 文件名
	 * @param scaleMX 缩放矩阵
	 * **/
	public static Bitmap getBitMapForceScale(String fileName,Matrix scaleMX){
		Bitmap bmp= getBitMap(fileName,scaleMX);//获取图片
		return bmp;
	}
	
	
	/**创建自适应屏幕的缩放图像
	 *@param image原图**/
	public static Bitmap createForceScaleBitmap(Bitmap image){
		return createForceScaleBitmap(image,scaleMX);
	}
	
	/**
	 * 获取原图
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitMap(String fileName){
		return getBitMap(fileName,null);
	}
	
	/**获取asset中的图片
	 * @param fileName 文件名
	 * @param scaleMX 缩放矩阵
	 * **/
	public static Bitmap getBitMap(String fileName,Matrix scaleMX){
		Bitmap bmp=null;
		try {
			 if (imageCache.containsKey(fileName)) { 
	            SoftReference<Bitmap> softReference = imageCache.get(fileName); 
	            bmp=softReference.get();
	            if(bmp!=null){
	            	 return bmp;
	            }
	            Log.i("imageInfos","图片缓存已被销毁:"+fileName);
		     }
			 
			Log.i("imageInfos","加载图片:"+fileName);
			 
			 //据说可以节约内存
			BitmapFactory.Options opt = new BitmapFactory.Options();
		    opt.inPreferredConfig = Bitmap.Config.RGB_565;
		    opt.inPurgeable = true;
		    opt.inInputShareable = true;
		    
    	    InputStream is=assetManager.open(fileName);
    	    bmp = BitmapFactory.decodeStream(is,null,opt);
    	    float w = bmp.getWidth();
			is.close();
			if(scaleMX!=null){
				bmp=createForceScaleBitmap(bmp,scaleMX);
			}
			w = bmp.getWidth();
			if(imageScaleMx!=null){
				bmp=createForceScaleBitmap(bmp,imageScaleMx);
			}
			w= bmp.getWidth();
			addToImagePool(fileName,new SoftReference<Bitmap>(bmp));
			return bmp;
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("infos", "找不到图片"+fileName);
			return bmp;
		}
	}
	
	/**创建缩放图像
	 *@param image原图
	 *@param mx矩阵 */
	public static Bitmap createForceScaleBitmap(Bitmap image,Matrix scaleMX){
		if(scaleMX!=null)
			return Bitmap.createBitmap(image,0,0,image.getWidth(),image.getHeight(),scaleMX,true);
		else 
			return image;
	}
	
	
	/**
	 * 添加到图片池中
	 */
	public synchronized static void addToImagePool(String fileName,SoftReference<Bitmap> sr){
		Log.i("imageInfos","添加到图片池:"+fileName);
		imageCache.put(fileName,sr);
	}
	
	/**
	 * 获取全屏宽 的图片 
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitmapFullScreenWidth(String fileName){
		 InputStream is = null;
		try {
			is = assetManager.open(fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 Bitmap bmp  = BitmapFactory.decodeStream(is);
		 if(imageScaleMx!=null){
				bmp=createForceScaleBitmap(bmp,imageScaleMx);
		 }
		 float bitmapWidth = bmp.getWidth();
		 float be = bitmapWidth/PhoneInfo.screenWidth_def;
		 float finalHeight = be*bmp.getHeight();
		 Bitmap result = Bitmap.createScaledBitmap(bmp, PhoneInfo.screenWidth_def, (int)finalHeight, true);
		 addToImagePool(fileName,new SoftReference<Bitmap>(result));
		 return result;
	}
	
	/**
	 * 获取全屏高的图片
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitmapFullScreenHeight(String fileName){
		 InputStream is = null;
		try {
			is = assetManager.open(fileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 Bitmap bmp  = BitmapFactory.decodeStream(is);
		 if(imageScaleMx!=null){
				bmp=createForceScaleBitmap(bmp,imageScaleMx);
		 }
		 float bitmapHeight = bmp.getHeight();
		 float be = bitmapHeight/PhoneInfo.screenHeight_def;
		 float finalWidth = be*bmp.getWidth();
		 Bitmap result = Bitmap.createScaledBitmap(bmp, (int)finalWidth,PhoneInfo.screenHeight_def,true);
		 addToImagePool(fileName,new SoftReference<Bitmap>(result));
		 return result;
	}
	
	
	/**
	 * 不加载图片的情况下获取图片大小
	 * @param fileName
	 * @return
	 */
	public static float[] getBitmapBoundsInfo(String fileName){
		float[] result = new float[2];
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bmp = BitmapFactory.decodeFile(fileName, options);
		result[0]=options.outWidth;
		result[1]=options.outHeight;
		return result;
	}
	
	/**
	 * 获取图片宽
	 * @param fileName
	 * @return
	 */
	public static float getBitmapWidth(String fileName){
		return getBitmapBoundsInfo(fileName)[0];
	}
	
	/**
	 * 获取图片高
	 * @param fileName
	 * @return
	 */
	public static float getBitmapHeight(String fileName){
		return getBitmapBoundsInfo(fileName)[1];
	}
	
	/**
	 * 自定义宽高
	 * @param fileName
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap getBitMap(String fileName,int width,int height){
		Bitmap bitmap = getBitMap(fileName);
		Bitmap result =  Bitmap.createScaledBitmap(bitmap, width, height, true);
		addToImagePool(fileName,new SoftReference<Bitmap>(result));
		return result ;
	}
	
	/**
	 * 把图片缩放为全屏大
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitMapFullScreen(String fileName){
		return getBitMap(fileName,PhoneInfo.screenWidth_def,PhoneInfo.screenHeight_def);
	}
	
	
	/**
	 * 切割不缩放
	 * @param fileName
	 * @param rows
	 * @param cols
	 * @return
	 */
	public static Bitmap[] CutImage(String fileName,int rows,int cols){
		return CutImage(fileName,rows,cols,false);
	}
	
	public static Bitmap[] CutImage(String fileName,int rows,int cols,boolean forceScale){
		if(forceScale){
			return CutImage(fileName,rows,cols,scaleMX);
		}else{
			return CutImage(fileName,rows,cols,null);
		}
	}
	
	/**
	 * 重载CutImage
	 * @param img 文件名
	 * @param rows 分割的行数
	 * @param cols 分割的列数
	 * @param scaleMX 缩放矩阵*/
	public static Bitmap[] CutImage(String fileName,int rows,int cols,Matrix scaleMX){
		Bitmap[] result = null;
		if(imageArrayCache.containsKey(fileName)){
			SoftReference<Bitmap[]> softReference = imageArrayCache.get(fileName);  
			result=softReference.get(); 
			if(result!=null){
				return result;
			}
		}
		//没有缓存或者已被回收
		Bitmap temp=getBitMap(fileName,scaleMX);
		int width=temp.getWidth()/cols;
		int height=temp.getHeight()/rows;
		result=CutImage(temp,width,height);
		imageArrayCache.put(fileName,  new SoftReference<Bitmap[]>(result));
		return result;
	}
	
	
	/**
	 * 切割图片
	 * @param img 原图
	 * @param width切割的宽
	 * @param width切割的高*
	 * @param scaleMX 缩放矩阵*/
	public static Bitmap[] CutImage(Bitmap img, int width, int height){
		//--纵向截取的个数
		int cols = img.getWidth() / width;
		//--横向截取的个数
		int rows = img.getHeight() / height;
		//计算要切割成多少个图片
		Bitmap images[] = new Bitmap[cols * rows];
		//--图片数组下标
		int k = 0;
		//外层循环行,内层循环列
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				//列的分割以width来计算,行的分割以height来计算
				Bitmap tem = Bitmap.createBitmap(img,j*width, i*height, width,height);
//				if(scaleMX!=null){//缩放图片
//					tem=createForceScaleBitmap(tem,scaleMX);
//				}
				images[k] = tem;
				k++;	
			}
		}
		return images; 
	}
	
	/*绘制数字*/
	public static void drawNumber(Canvas canvas,Bitmap[] numImage,int num,int x, int y){
		canvas.drawBitmap(numImage[num],x,y,paint);
	}
	
	
	public static void drawColorFullScreenColor(Canvas canvas ,int color){
		canvas.save();
		canvas.clipRect(getScreenRect());
		canvas.drawColor(color);
		canvas.restore();
	}
	
	
	public static Rect getScreenRect(){
		Rect rec= new Rect(PhoneInfo.startScreenX, PhoneInfo.startScreenY,
				PhoneInfo.endScreenX,PhoneInfo.endScreenY);
		return rec;
	}
	
	public static RectF getLayerRect(BasicLayer layer){
		float[] region = layer.getBasicRegion().getRegionXY();
		RectF rectf = new RectF(region[0],region[1],region[2],region[3]);
		return rectf;
	}
	
	
	//--------------------------------------------中央
	/**把图片画在屏幕中央
	 * @param image 位图**/
	public static float[] drawImgCenter(Canvas canvas,Bitmap image){
		return drawImgCenter(canvas,image,null);
	}
	
	/**把图片画在屏幕中央,自带画笔
	 * @param image 位图
	 * @param p 自定义画笔**/
	public static float[] drawImgCenter(Canvas canvas,Bitmap image,Paint p){
		if(p==null)
			p=paint;
		float x= PhoneInfo.screenWidthHalf_def-image.getWidth()/2;
		float y= PhoneInfo.screenHeightHalf_def-image.getHeight()/2;
		canvas.drawBitmap(image,x,y,p);
		return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
	}
	
	//--------------------------------------------左上
	/**把图片画在屏幕左上角
	 * @param image 位图**/
	public static float[] drawImgTopLeft(Canvas canvas,Bitmap image){
		return drawImgTopLeft(canvas,image,null);
	}
	
	/**把图片画在屏幕左上角
	 * @param image 位图
	 * @param p 自定义画笔**/
	public static float[] drawImgTopLeft(Canvas canvas,Bitmap image,Paint p){
		if(p==null)
			p=paint;
		float x= PhoneInfo.startScreenX_def;
		float y= PhoneInfo.startScreenY_def;
		canvas.drawBitmap(image,x,y,p);
		return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
	}
	
	
	//--------------------------------------------右上
	/**把图片画在屏幕右上角
	 * @param image 位图**/
	public static float[] drawImgTopRight(Canvas canvas,Bitmap image){
		return drawImgTopRight(canvas,image,null);
	}
	
	/**把图片画在屏幕右上角
	 * @param image 位图
	 * @param p 自定义画笔**/
	public static float[] drawImgTopRight(Canvas canvas,Bitmap image,Paint p){
		if(p==null)
			p=paint;
		float x= PhoneInfo.endScreenX_def-image.getWidth();
		float y= PhoneInfo.startScreenY_def;
		canvas.drawBitmap(image,x,y,p);
		return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
	}
	
	//--------------------------------------------左下
		/**把图片画在屏幕左下角
		 * @param image 位图**/
		public static float[] drawImgBtoomtLeft(Canvas canvas,Bitmap image){
			return drawImgBtoomtLeft(canvas,image,null);
		}
		
		/**把图片画在屏幕左下角
		 * @param image 位图
		 * @param p 自定义画笔**/
		public static float[] drawImgBtoomtLeft(Canvas canvas,Bitmap image,Paint p){
			if(p==null)
				p=paint;
			float x= PhoneInfo.startScreenX_def;
			float y= PhoneInfo.endScreenY_def-image.getHeight();
			canvas.drawBitmap(image,x,y,p);
			return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
		}
		
		
		//--------------------------------------------右下
		/**把图片画在屏幕右下角
		 * @param image 位图**/
		public static float[] drawImgBottomRight(Canvas canvas,Bitmap image){
			return drawImgBottomRight(canvas,image,null);
		}
		
		/**把图片画在屏幕右下角
		 * @param image 位图
		 * @param p 自定义画笔**/
		public static float[] drawImgBottomRight(Canvas canvas,Bitmap image,Paint p){
			if(p==null)
				p=paint;
			float x= PhoneInfo.endScreenX-image.getWidth();
			float y= PhoneInfo.endScreenY-image.getHeight();
			canvas.drawBitmap(image,x,y,p);
			return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
		}
		//--------------------------------------------指定图片的中央
		/**把图片画在屏幕右下角
		 * @param image 位图**/
		public static float[] drawImgCenterImage(Canvas canvas,Bitmap image,Bitmap imageBg,float postx,float posty){
			return drawImgCenterImage(canvas,image,imageBg,postx,posty);
		}
		
		/**把图片画在屏幕右下角
		 * @param image 位图
		 * @param p 自定义画笔**/
		public static float[] drawImgCenterImage(Canvas canvas,Bitmap image,Bitmap imageBg,float postx,float posty,Paint p){
			if(p==null)
				p=paint;
			float x= (imageBg.getWidth()-image.getWidth())/2+postx;
			float y= (imageBg.getHeight()-image.getHeight())/2+postx;
			canvas.drawBitmap(image,x,y,p);
			return new float[]{x,y,x+image.getWidth(),y+image.getHeight()};
		}
		
		
//		/**获取asset中被加密的图片
//		 * @param fileName 文件名**/
//		public static Bitmap getBitMap(String fileName){
//			try {
//				InputStream codedStream=assetManager.open(fileName);
//				BufferedInputStream bis = new BufferedInputStream(codedStream);
////				DataInputStream dis=new DataInputStream(bis);
//				ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
//			    byte[] buffer = new byte[1024];
//		        int len=0;
//		        while ((len = bis.read(buffer)) > 0) { 
//		        	bos.write(buffer,0,len);
//		        }            
//		        byte[] dat = bos.toByteArray();
//		        codedStream.close();
//		        bis.close();
////		        dis.close();
//		        bos.close();
//			    //读取有效数据
//			    Bitmap bmp=BitmapFactory.decodeByteArray(dat,pre_length, dat.length-(pre_length+beh_length));
//				return bmp;
//			} catch (IOException e) {
//				e.printStackTrace();
//				Log.i("infos", "找不到图片"+fileName);
//				return null;
//			}
//		}
		
	
}